import 'package:flutter/material.dart';
import 'dart:developer' as developer;

///
///
///
/// ScrollController
/// 滚动监听及控制
/// https://api.flutter-io.cn/flutter/widgets/ScrollView/controller.html
///
///  主要监听滑动变化，支持一个控制器支持多个滑动组件
///  支持滑动和跳转响应的位置
///
///
class ListViewControllerViewPage extends StatefulWidget {


  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return ShowListViewSate();
  }


}

class ShowListViewSate extends State<ListViewControllerViewPage> {
  final ScrollController _scrollController = ScrollController();

  bool showToTopBtn = false;

  ShowListViewSate();


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    var size = 40;
    return Scaffold(
        appBar: AppBar(
          title: Text("滚动监听及控制"),
        ),
        body: ListView.builder(
          itemCount: 40,
          itemBuilder: (context, index) {
            return ListTile(
              leading: const FlutterLogo(
                size: 40,
              ),
              title: Text("序号${index + 1}"),
            );
          },
          prototypeItem: const ListTile(
            leading: FlutterLogo(
              size: 40,
            ),
            title: Text("序号1"),
          ),
          controller: _scrollController,
        ),
        floatingActionButton: showToTopBtn ? FloatingActionButton(
            child: Icon(Icons.reviews),
            onPressed: () {
              _scrollController.animateTo(
                .0,
                duration: Duration(milliseconds: 200),
                curve: Curves.ease,
              );
            }
        ):null
    );
  }



  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _scrollController.addListener(() {
      developer.log("偏移量：${_scrollController.offset}");

      if (_scrollController.offset < 1000 && showToTopBtn) {
        setState(() {
          showToTopBtn = false;
        });
      } else if (_scrollController.offset >= 1000 && showToTopBtn == false) {
        setState(() {
          showToTopBtn = true;
        });
      }
    });
  }


  @override
  void dispose() {
    // TODO: implement dispose
    _scrollController.dispose();
    super.dispose();
    
  }

}
